package com.leetcode.a002;

/**
 * @author zhengqn
 * @Title: AddTwoNumbers
 * @Description: 两数相加
 * @date 2019/12/19 10:15
 */
public class AddTwoNumbers {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 进位值，初始化为0
        int quotient = 0;
        // 新返回的链表
        ListNode res = new ListNode(0);
        // cur指向新链表，随着计算后移，总是指向最后一位节点
        ListNode cur = res;
        // 两个链表没有到结束或者进位值不为0都需要进行遍历
        while(l1 != null || l2 != null || quotient != 0){
            int temp = ((l1 == null)? 0 : l1.val) + ((l2 == null) ? 0 : l2.val) +quotient;
            cur.next = new ListNode(temp % 10);
            cur = cur.next;
            quotient = temp / 10;
            l1 = (l1 == null)? null : l1.next;
            l2 = (l2 == null)? null : l2.next;
        }
        return res.next;
    }


}
